/**
 * @author Luc Yriarte
 * 
 * Licence : BSD http://www.opensource.org/licenses/bsd-license.php
 *  
 */
package basicSim;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;

public class ComplexPlan {

	public int n;
	public double e;	// [-e/2 .. e/2]
	public Complex cell[][]; // n * n
	public Image image;

	public ComplexPlan(int nLines, double extent, double minX, double minY, Image img) {
		n = nLines;
		e = extent;
		cell = new Complex[n][n];
		image = img;
		int i,j;
		double step, a, b;
		step = extent / n;
System.out.println("ComplexPlan n=" + n + " extent=" + e + " minX=" + minX + " minY=" + minY);
		a = minX;
		for (i=0; i<n; i++) {
			b = minY;
			for (j=0; j<n; j++) {
				cell[i][j] = new Complex(a,b);
				b += step;
			}
			a += step;
		}
	}

	public void drawMandelbrot(int max, int mask) {
		int i,j,k,colorstep,kc;
		Complex c, z;
		Graphics g = image.getGraphics();
		Color color;
		if (mask == 0)
			colorstep = 0x00FFFFFF / max;
		else
			colorstep = Math.max(0xFF/max,1);
		System.out.println("ComplexPlan drawMandelbrot max=" + max + " colorstep=" + colorstep);
		for (i=0; i<n; i++) {
			for (j=0; j<n; j++) {
				c = cell[i][j];
				z = new Complex();
				for (k=0; k<max; k++) {
					if (z.mod > 2)
						break;
					z = (z.mul(z)).add(c);
				}
				if (k==max)
					color = new Color(0);
				else {
					kc = k * colorstep;
					if (mask==0)
						color = new Color(kc);
					else
						color = new Color((kc | (kc << 8) | (kc << 16) ) & mask);
				}
//System.out.println("(" + i + "," + j + ") : " + color.toString());
				g.setColor(color);
				g.drawLine(i,j,i,j);
			}
		}
	}
}
